package com.sk.weichat.ui.mucfile;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.R;
import com.sk.weichat.bean.EmptyData;
import com.sk.weichat.ui.base.LazyFragment;
import com.sk.weichat.ui.mucfile.adapter.DividerAdapter;
import com.sk.weichat.ui.mucfile.adapter.EmptyAdapter;
import com.sk.weichat.ui.mucfile.adapter.FileAdapter;
import com.sk.weichat.ui.mucfile.adapter.TypeAdapter;
import com.sk.weichat.ui.mucfile.bean.FileBean;
import com.sk.weichat.util.MediaHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.sk.weichat.ui.mucfile.AddMucFileActivity2.Action_Click;
import static com.sk.weichat.ui.mucfile.bean.FileBean.ZIP;

public class MediaOtherFragment2 extends LazyFragment implements MediaHelper.OnQueryListener {

    SmartRefreshLayout refreshLayout;
    private List<DelegateAdapter.Adapter> adapterList = new ArrayList<>();
    EmptyData emptyData = new EmptyData("该分类暂无内容");

    private DelegateAdapter delegateAdapter;

    //记录展开的项
    Map<String, Boolean> expandMap = new HashMap<>();
    //记录选择的Item
    Map<String, Boolean> checkedMap = new HashMap<>();
    private boolean once = false;
    List<FileBean> zipBeans = new ArrayList<>();
    List<FileBean> txtBeans = new ArrayList<>();
    List<FileBean> otherBeans = new ArrayList<>();

    private FileAdapter zipAdapter;
    private FileAdapter txtAdapter;
    private FileAdapter otherAdapter;
    private TypeAdapter zipTypeAdapter;
    private TypeAdapter txtTypeAdapter;
    private TypeAdapter otherTypeAdapter;


    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_media_other;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public void loadData() {
        //扫描文件时间过长，缓存不为空，显示缓存
        List<File> files = MediaHelper.getInstance().getFilesQueryCache();
        if (files != null) {
            onDataSuccess(files);
        } else {
            refreshLayout.autoRefresh();
        }
    }


    private void realLoadData() {
        //查询
        MediaHelper.getInstance().getMediaFiles(getActivity().getContentResolver(), this);
    }

    @Override
    protected void initView(View view) {
        refreshLayout = view.findViewById(R.id.refresh_layout);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                realLoadData();
            }
        });
        VirtualLayoutManager layoutManager = new VirtualLayoutManager(getActivity());

        RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(layoutManager);
        delegateAdapter = new DelegateAdapter(layoutManager, false);

        recyclerView.setAdapter(delegateAdapter);
        initAdapter(mContext);

    }


    private void initAdapter(Context context) {
        zipAdapter = new FileAdapter(context, new ArrayList<>());
        zipAdapter.setOnFileBeanClickListener(new FileAdapter.OnFileBeanClickListener() {
            @Override
            public void onClick(FileBean fileBean, int pos) {
                selectItem(fileBean);
                zipAdapter.notifyItemChanged(pos);
            }
        });
        txtAdapter = new FileAdapter(context, new ArrayList<>());
        txtAdapter.setOnFileBeanClickListener(new FileAdapter.OnFileBeanClickListener() {
            @Override
            public void onClick(FileBean fileBean, int pos) {
                selectItem(fileBean);
                txtAdapter.notifyItemChanged(pos);
            }
        });
        otherAdapter = new FileAdapter(context, new ArrayList<>());
        otherAdapter.setOnFileBeanClickListener(new FileAdapter.OnFileBeanClickListener() {
            @Override
            public void onClick(FileBean fileBean, int pos) {
                selectItem(fileBean);
                otherAdapter.notifyItemChanged(pos);
            }
        });

        List<FileBean> fileBeans = new ArrayList<>();
        FileBean fileBean = new FileBean();
        fileBean.setType(FileBean.DIR);
        fileBean.setTypeName("压缩文件");
        fileBean.setExpand(expandMap.get(fileBean.getTypeName()) == null ? false : expandMap.get(fileBean.getTypeName()));
        if (!once) {
            //首次加载展开第一项
            once = true;
            fileBean.setExpand(true);
            expandMap.put(fileBean.getTypeName(), true);
        }
        fileBeans.add(fileBean);
        zipTypeAdapter = new TypeAdapter(context, fileBeans);

        zipTypeAdapter.setOnTypeClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (zipTypeAdapter.getData().get(0).isExpand()) {
                    zipTypeAdapter.getData().get(0).setExpand(false);
                    zipTypeAdapter.notifyItemChanged(0);
                    expandMap.put(zipTypeAdapter.getData().get(0).getTypeName(), false);
                    //折叠
                    zipAdapter.getData().clear();
                    zipAdapter.notifyItemRangeRemoved(0, zipBeans.size());
                } else {
                    //展开
                    zipTypeAdapter.getData().get(0).setExpand(true);
                    zipTypeAdapter.notifyItemChanged(0);
                    expandMap.put(zipTypeAdapter.getData().get(0).getTypeName(), true);
                    zipAdapter.getData().addAll(zipBeans);
                    zipAdapter.notifyItemRangeInserted(0, zipBeans.size());
                }
            }
        });


        List<FileBean> fileBeans1 = new ArrayList<>();
        FileBean fileBean1 = new FileBean();
        fileBean1.setType(FileBean.DIR);
        fileBean1.setTypeName("电子书");
        fileBean1.setExpand(expandMap.get(fileBean1.getTypeName()) == null ? false : expandMap.get(fileBean1.getTypeName()));
        fileBeans1.add(fileBean1);
        txtTypeAdapter = new TypeAdapter(context, fileBeans1);

        txtTypeAdapter.setOnTypeClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (txtTypeAdapter.getData().get(0).isExpand()) {
                    txtTypeAdapter.getData().get(0).setExpand(false);
                    expandMap.put(txtTypeAdapter.getData().get(0).getTypeName(), false);
                    txtTypeAdapter.notifyItemChanged(0);

                    //折叠
                    txtAdapter.getData().clear();
                    txtAdapter.notifyItemRangeRemoved(0, txtBeans.size());
                } else {
                    //展开
                    txtTypeAdapter.getData().get(0).setExpand(true);
                    txtTypeAdapter.notifyItemChanged(0);
                    expandMap.put(txtTypeAdapter.getData().get(0).getTypeName(), true);
                    txtAdapter.getData().addAll(txtBeans);
                    txtAdapter.notifyItemRangeInserted(0, txtBeans.size());
                }
            }
        });

        List<FileBean> fileBeans2 = new ArrayList<>();
        FileBean fileBean2 = new FileBean();
        fileBean2.setType(FileBean.DIR);
        fileBean2.setTypeName("更多");
        fileBean2.setExpand(expandMap.get(fileBean2.getTypeName()) == null ? false : expandMap.get(fileBean2.getTypeName()));
        fileBeans2.add(fileBean2);
        otherTypeAdapter = new TypeAdapter(context, fileBeans2);

        otherTypeAdapter.setOnTypeClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (otherTypeAdapter.getData().get(0).isExpand()) {
                    otherTypeAdapter.getData().get(0).setExpand(false);
                    expandMap.put(otherTypeAdapter.getData().get(0).getTypeName(), false);
                    otherTypeAdapter.notifyItemChanged(0);
                    //折叠
                    otherAdapter.getData().clear();
                    otherAdapter.notifyItemRangeRemoved(0, otherBeans.size());
                } else {
                    //展开
                    otherTypeAdapter.getData().get(0).setExpand(true);
                    expandMap.put(otherTypeAdapter.getData().get(0).getTypeName(), true);
                    otherTypeAdapter.notifyItemChanged(0);
                    otherAdapter.getData().addAll(otherBeans);
                    otherAdapter.notifyItemRangeInserted(0, otherBeans.size());
                }
            }
        });
    }

    private void selectItem(FileBean fileBean) {
        if (AddMucFileActivity2.isAllowToSelect() || fileBean.isChecked()) {
            fileBean.setChecked(!fileBean.isChecked());
            checkedMap.put(fileBean.getFile().getAbsolutePath(), fileBean.isChecked());
            //发送广播
            Intent intent = new Intent();
            intent.setAction(Action_Click);
            intent.putExtra(FileBean.FileBean_Key, fileBean);
            LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
        } else {
            Toast.makeText(mContext, mContext.getString(R.string.select_file_count_place_holder, 9), Toast.LENGTH_SHORT).show();
        }
    }


    private void onDataSuccess(List<File> files) {
        Observable.create(new ObservableOnSubscribe<Object>() {

            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                //耗时操作
                try {
                    fillData(files);
                    addAdapter();
                } catch (Exception e) {
                    emitter.onError(e);
                }
                emitter.onNext(new Object());
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {

                    @Override
                    public void accept(Object o) throws Exception {
                        delegateAdapter.clear();
                        delegateAdapter.setAdapters(adapterList);
                        delegateAdapter.notifyDataSetChanged();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                });
    }

    /**
     * 重新调整位置
     */
    private void addAdapter() {
        adapterList.clear();
        if (zipBeans.size() > 0) {
            adapterList.add(zipTypeAdapter);
            adapterList.add(zipAdapter);
            adapterList.add(new DividerAdapter(mContext));
        }
        if (txtBeans.size() > 0) {
            adapterList.add(txtTypeAdapter);
            adapterList.add(txtAdapter);
            adapterList.add(new DividerAdapter(mContext));
        }
        if (otherBeans.size() > 0) {
            adapterList.add(otherTypeAdapter);
            adapterList.add(otherAdapter);
            adapterList.add(new DividerAdapter(mContext));
        }
        if (zipBeans.size() == 0 && txtBeans.size() == 0 && otherBeans.size() == 0) {
            //无数据加载无数据页面
            adapterList.add(new EmptyAdapter(mContext));
        }
    }

    private void fillData(List<File> files) {
        for (int i = 0; i < files.size(); i++) {
            File file = files.get(i);
            String suffix = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".") + 1, file.getAbsolutePath().length());
            FileBean fileBean = new FileBean();
            fileBean.setFileName(file.getName());
            fileBean.setFile(file);
            fileBean.setChecked(checkedMap.get(file.getAbsolutePath()) == null ? false : checkedMap.get(file.getAbsolutePath()));
            if ((suffix.equalsIgnoreCase("zip") || suffix.equalsIgnoreCase("rar")) && file.length() > 1024) {
                fileBean.setType(ZIP);
                zipBeans.add(fileBean);
                if (zipTypeAdapter.getData().get(0).isExpand()) {
                    zipAdapter.getData().add(fileBean);
                }
            } else if ((suffix.equalsIgnoreCase("txt") || suffix.equalsIgnoreCase("rtf")) && file.length() > 1024) {
                fileBean.setType(FileBean.TXT);
                txtBeans.add(fileBean);
                if (txtTypeAdapter.getData().get(0).isExpand()) {
                    txtAdapter.getData().add(fileBean);
                }
            } else if (suffix.equalsIgnoreCase("cad") && file.length() > 1024) {
                fileBean.setType(FileBean.FILE);
                otherBeans.add(fileBean);
                if (otherTypeAdapter.getData().get(0).isExpand()) {
                    otherAdapter.getData().add(fileBean);
                }
            }

        }
    }

    @Override
    public void onSuccess(List<File> files) {
        refreshLayout.finishRefresh();
        onDataSuccess(files);
    }

    @Override
    public void onFailed(String msg) {
        refreshLayout.finishRefresh();
    }
}
